package com.example.iread.util;

import com.example.iread.bean.BookBean;
import com.example.iread.exception.MyException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.List;

public final class GsonUtil {

    public static <T> T parseObject(Object object, Class<T> type) {
        return new Gson().newBuilder().serializeNulls().create().fromJson(new Gson().toJson(object), type);
    }

    @SuppressWarnings("unchecked")
    public static <T> T parseObject(Object data, Type type) {
        Gson gson = new Gson();
        TypeAdapter<T> adapter = (TypeAdapter<T>) gson.getAdapter(TypeToken.get(type));
        JsonReader jsonReader = gson.newJsonReader(new StringReader(gson.toJson(data)));
        try {
            return adapter.read(jsonReader);
        } catch (IOException e) {
            throw new MyException(500, e.getMessage());
        }
    }
}
